let fs = require('mz/fs');
let path = require('path');

// async await 版
async function wideDir(url) {
    let arr = [url]
    let index = 0;
    let current;
    while (current = arr[index++]) {
        let statObj = await fs.stat(current)
        if (statObj.isDirectory()) {
            let dirs = await fs.readdir(current)
            dirs = dirs.map(dir => path.join(current, dir))
            arr = [...arr, ...dirs];
        } else {
            arr.splice(index-1, 1)
            index--
            await fs.unlink(current)
        }    
    }
    for (let i = arr.length - 1; i >= 0; i--) {
        await fs.rmdir(arr[i])
    }
}

// promise版
function wideDir(url) {
    return new Promise((resolve, reject) => {
        let arr = [url];
        let index = 0;
        function next(current) {
            if (!arr[index]) {
                function rmdir () {
                    if (index <= 0) return resolve()
                    let p = arr[--index]
                    fs.rmdir(p).then(() => {
                        rmdir()
                    })    
                }
                rmdir()
                return
            }
            index++
            fs.stat(current).then((statObj) => {
                if (statObj.isFile()) {
                    fs.unlink(current).then((res) => {
                        arr.splice(index - 1, 1)
                        index--
                        next(arr[index])
                    })
                } else {
                    fs.readdir(current).then((dirs) => {
                        dirs = dirs.map(dir => path.join(current, dir))
                        arr = [...arr, ...dirs]
                        next(arr[index])
                    }, reject)
                }
            }, reject)    
        }
        next(url);
    })
}

wideDir('a').then(() => {
    console.log('删除成功')
})